﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using StockMatch.Service.AOPCustomAchieve;

namespace StockMatch.Service
{
    public class ConfigRelationExecution
    {
        private static Dictionary<string, AOPConfig> _ConfigRelation;

        public static Dictionary<string, AOPConfig> ConfigRelation
        {
            get 
            {
                if (_ConfigRelation == null)
                {
                    _ConfigRelation = new Dictionary<string, AOPConfig>();
                }
                return _ConfigRelation;
            }
        }

        public static void ActionConfigByAspectName(string aspectname, string methodname,string typeName, InterceptAchieveType interceptAchieveType, IMessage msg)
        {
            if (_ConfigRelation.ContainsKey(aspectname))
            {
                AOPConfig config = _ConfigRelation[aspectname];
                string[] typeNames = typeName.Split(new char[] { ','},StringSplitOptions.RemoveEmptyEntries);
                string mname = string.Format("{0}.{1}",typeNames[0],methodname);
                if (config.MethodNameList.Contains(mname))
                {
                    if (config.AOPInterceptAchieve != null)
                    {
                        if (config.InterceptActhieveType == InterceptAchieveType.All)
                        {
                            InterceptAchieve(interceptAchieveType, config.AOPInterceptAchieve, msg);
                        }
                        else if (config.InterceptActhieveType == interceptAchieveType)
                        {
                            InterceptAchieve(interceptAchieveType, config.AOPInterceptAchieve, msg);
                        }
                    }
                }
            }
        }

        private static void InterceptAchieve(InterceptAchieveType interceptAchieveType, AOPInterceptAchieve aopInterceptAchieve,IMessage msg)
        {
            if (interceptAchieveType == InterceptAchieveType.Before)
            {
                IBeforeAchieve beforeAchieve = aopInterceptAchieve as IBeforeAchieve;
                if (beforeAchieve != null)
                {
                    beforeAchieve.BeforeAchieve((IMethodCallMessage)msg);
                }
            }
            else
            {
                IAfterAchieve beforeAchieve = aopInterceptAchieve as IAfterAchieve;
                if (beforeAchieve != null)
                {
                    beforeAchieve.AfterAchieve((IMethodReturnMessage)msg);
                }
            }
        }
    }
}
